<!-- 入库 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">配置规则</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">规则类型</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<HsForm :filed-list="ruleTypeList" ref="ruleType" :isDisabled="isReadOnly"></HsForm>
					</div>
					<!-- card2 -->
					<div class="zs-align-center zs-space-bottom zs-space-top-lg" id="sm-drawer-demo-card-02">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">规则信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<HsForm :filed-list="ruleInfoList" ref="ruleInfo" :isDisabled="isReadOnly" @selectChange="selectChange"></HsForm>
					</div>
					<!-- card3 -->
					<div class="zs-align-center zs-space-bottom zs-space-top-lg" id="sm-drawer-demo-card-03">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">触发频率</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<HsForm :filed-list="ruleFrequencyList" ref="ruleFrequency" :isDisabled="isReadOnly" @blurFn="blurFn"></HsForm>
					</div>
					<!-- card4 -->
					<div class="zs-align-center zs-space-bottom zs-space-top-lg" id="sm-drawer-demo-card-04">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">是否开启</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<HsForm :filed-list="ruleOpenList" ref="ruleOpen" :isDisabled="isReadOnly"></HsForm>
					</div>
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import HsForm from '@/components/hsForm.vue';
	import { ruleTypeList, ruleInfoListBJCH, ruleInfoPropertyAreaList, ruleFrequencyList, ruleOpenList } from '@/config/form/energy.js';
	import { ref, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import Energy from '@/api/Energy';
	import { getPropertyDictoryApi } from '@/api/dbPublic';
	import { setFormSelectOptions } from '@/utils/formEvent';
	import { deepClone } from '@/utils/publicUtils';
	import { ElMessage } from 'element-plus';

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});
	const store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	const emit = defineEmits(['close']);
	let isShowDrawer = ref(props.isShow);
	const ruleInfoList = props.currentRow.type == 1 ? ruleInfoListBJCH : ruleInfoPropertyAreaList;
	const curNodeList = ref([
		{ name: '规则类型', id: 'sm-drawer-demo-card-01' },
		{ name: '规则信息', id: 'sm-drawer-demo-card-02' },
		{ name: '触发频率', id: 'sm-drawer-demo-card-03' },
		{ name: '是否开启', id: 'sm-drawer-demo-card-04' },
	]);
	const ruleType = ref();
	const ruleInfo = ref();
	const ruleFrequency = ref();
	const ruleOpen = ref();

	watch(
		() => props.isShow,
		newVal => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
				newVal && props.handleType == 'edit' && getInfo();
			});
		},
	);

	//详情
	const configInfo = ref({});
	const getInfo = async () => {
		initRuleTypeList();
		controlFiled();
		let res = await Energy.mainConfigInfoApi({ id: props.currentRow.id });
		let resData = Object.assign(res.data.data);
		resData.ruleType = String(resData.ruleType);
		configInfo.value = resData;
		setFiledVal(ruleTypeList, ruleType);
		setFiledVal(ruleInfoPropertyAreaList, ruleInfo);
		setFiledVal(ruleFrequencyList, ruleFrequency);
		setFiledVal(ruleOpenList, ruleOpen);
	};

	//详情找到每个form应该有的字段
	const setFiledVal = (sourceList, refName) => {
		let filedNameList = sourceList.map(item => item.bindFieldName);
		let resultObj = {};
		for (let i in configInfo.value) {
			if (filedNameList.includes(i)) {
				resultObj[i] = configInfo.value[i];
			}
		}
		refName.value.setFiledVal(resultObj);
	};

	//提交
	const doConfirm = async () => {
		let modleRule = await ruleType.value.validateForm();
		let modleInfo = await ruleInfo.value.validateForm();
		let modleFrequency = await ruleFrequency.value.validateForm();
		let modleOpen = await ruleOpen.value.validateForm();
		if (!modleRule || !modleInfo || !modleFrequency || !modleOpen) return;
		//校验是否有Cron解析结果  没有 或者 没解析过不允许提交
		if (!modleFrequency.frequencyStr) {
			ElMessage({ message: '请填写解析Cron表达式', type: 'warning' });
			return;
		}
		let params = Object.assign(modleRule, modleInfo, modleFrequency, modleOpen);
		params.id = configInfo.value.id || '';
		let res = props.handleType == 'add' ? await Energy.mainConfigAddApi(params) : await Energy.mainConfigEditApi(params);
		if (res.data.code != 200) return;
		ElMessage({ message: '提交成功', type: 'success' });
		isShowDrawer.value = false;
		emit('close', { isShow: false, isRefresh: true });
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	//表单初始化
	const initForm = () => {
		configInfo.value = {};
		controlFiled();
		initRuleTypeList();
		ruleType.value.resetFields();
		ruleInfo.value.resetFields();
		ruleFrequency.value.resetFields();
		ruleOpen.value.resetFields();
	};

	//编辑时规则类型禁止选择
	const controlFiled = () => {
		ruleTypeList.forEach(item => {
			item.isDisabled = props.handleType == 'edit' ? true : false;
		});
	};

	//form item change
	const selectChange = data => {
		if (data.filedName == 'status') {
			if (data.filedVal == 1) {
				data.setFiledSource('no', '');
			}
		}
	};

	//form item blur
	const blurFn = async data => {
		if (data.filedName == 'jobCron') {
			if (!data.filedVal) return;
			let res = await Energy.parseFrequencyApi({ frequency: data.filedVal });
			data.setFiledSource('frequencyStr', res.data.data.frequencyStr);
		}
	};

	//规则类型
	const ruleList = ref([]);
	const getRuleTypeList = async () => {
		let res = await getPropertyDictoryApi({ sort: true, delFalg: 0 });
		ruleList.value = res.data.data.ENERGY_METER_CONFIG_RULE_TYPE || [];
	};

	//新增的时候只展示物业-公区分类 隐藏其他的
	const initRuleTypeList = () => {
		let list = deepClone(ruleList.value);
		list.forEach(item => {
			if (['1', '2'].includes(item.dicValue)) {
				item.ifCanChecked = props.handleType == 'add' ? false : true;
			} else {
				item.ifCanChecked = true;
			}
		});
		setFormSelectOptions(ruleTypeList, 'ruleType', list);
	};

	getRuleTypeList();
</script>
